﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using MyServer.TcpIP;
using MyServer.Common;
using System.Net;
using System.Net.Sockets;
using ScreenMonitor.Common;
using ScreenMonitor.ServerLib;
using ServerUI.Setting;
using FrameWork.Setting;
using ScreenMonitor.ServerLib.Command;
using FrameWork.Plugin;
using ScreenMonitor.ServerLib.Plugin;

namespace ServerUI
{
    public partial class MainWnd : Form
    {
        public MainWnd()
        {
            InitializeComponent();
        }

        private void tbtnStop_Click(object sender, EventArgs e)
        {
            if (!(ServerMain.GetState() == ServerState.Started))
            {
                MessageBox.Show("服务端未启动！");
                return;
            }
            ServerMain.Stop();
            if (ServerMain.GetState() == ServerState.Stoped)
            {
                monset.Enabled = false;
                toolcliset.Enabled = false;
                ManagerMenu.Enabled = false;
                PingTimer.Stop();
                MessageBox.Show("停止服务端成功！");
            }
            else
            {
                MessageBox.Show("停止服务端失败！");
            }

        }

        private void tbtnStart_Click(object sender, EventArgs e)
        {
            if (ServerMain.GetState() == ServerState.Inited || ServerMain.GetState() == ServerState.Stoped)
            {
                ServerMain.Start();
            }
            else if (ServerMain.GetState() == ServerState.Started)
            {
                MessageBox.Show("服务端已经启动！");
                return;
            }
            if (ServerMain.GetState() == ServerState.Started)
            {
                MessageBox.Show("启动服务端成功！");
                monset.Enabled = true;
                toolcliset.Enabled = true;
                ManagerMenu.Enabled = true;
                PingTimer.Start();
            }
            else
            {
                MessageBox.Show("启动服务端失败！");
                monset.Enabled = false;
                toolcliset.Enabled = false;
                ManagerMenu.Enabled = false;
            }

        }

        private void tbtnRestart_Click(object sender, EventArgs e)
        {
            if (!(ServerMain.GetState() == ServerState.Started))
            {
                MessageBox.Show("服务端未启动！");
                return;
            }
            ServerMain.Restert();
            if (ServerMain.GetState() == ServerState.Started)
            {
                monset.Enabled = true;
                toolcliset.Enabled = true;
                ManagerMenu.Enabled = true;
                PingTimer.Start();
                MessageBox.Show("重启服务端成功！");
            }
            else
            {
                MessageBox.Show("重启服务端失败！");
            }
        }

        private IDockContent GetContent(string SetString)
        {
            if (SetString == typeof(ServerStats).ToString())
            {
                return Program.ServerStats;
            }
            else if (SetString == typeof(ClientList).ToString())
            {
                return Program.ClientList;
            }
            else if (SetString == typeof(ClientManagerWnd).ToString())
            {
                return Program.ClientManager;
            }
            else if (SetString == typeof(ProperWnd).ToString())
            {
                return Program.ProperWnd;
            }
            else if (SetString == typeof(OutputWnd).ToString())
            {
                return Program.OutputWnd;
            }
            else
            {
                foreach(IServerPlugin Plu in PluginPool.GetPlugins())
                {
                    if(SetString==Plu.GetPluginWindow().GetType().ToString())
                    {
                        return (IDockContent)Plu.GetPluginWindow();
                    }
                }
            }
            return null;
        }

        private void MainWnd_Load(object sender, EventArgs e)
        {
            this.IsMdiContainer = true;
            ScreenMonitor.ServerLib.ClientManager.AfterOperateClient += ClientManager_AfterOperateClient;
            try
            {
                ServerMain.Init();
            }
            catch (Exception ex)
            {
                SettingPool.RegisterEditor(Program.ServerUISettingEditorItem);
                SettingPool.LoadSetting();
                if (MessageBox.Show("服务端初始化失败：" + ex.Message + "\r\n单击确定检查设定后重启程序，点击取消立即退出程序", "程序初始化失败", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                {
                    Program.SettingWnd.ShowDialog();
                    Application.Restart();
                }
                else
                {
                    Application.Exit();
                }
            }
            SettingPool.RegisterEditor(Program.ServerUISettingEditorItem);
            SettingPool.LoadSetting();
            bool IsLayoutFileExist=System.IO.File.Exists(Application.StartupPath + "\\Layout.config");
            if (IsLayoutFileExist)
            {
                this.MainDockPanel.LoadFromXml(Application.StartupPath + "\\Layout.config", new DeserializeDockContent(GetContent));
            }
            else
            {

                Program.ServerStats.Owner = this;
                Program.ClientList.Owner = this;
                Program.ClientManager.Owner = this;
                Program.ProperWnd.Owner = this;
                Program.OutputWnd.Owner = this;
                Program.ServerStats.Show(this.MainDockPanel, DockState.DockRight);
                Program.ClientManager.Show(this.MainDockPanel, DockState.Document);
                Program.ClientList.Show(this.MainDockPanel, DockState.DockLeft);
                Program.ProperWnd.Show(this.MainDockPanel, DockState.DockLeft);
                Program.OutputWnd.Show(this.MainDockPanel, DockState.DockBottom);
            }
            foreach (IServerPlugin Plu in PluginPool.GetPlugins())
            {
                if (Plu.GetPluginWindow() != null)
                {
                    if (!IsLayoutFileExist)
                    {
                        if (Plu.GetPluginWindow().GetType().BaseType == typeof(DockContent))
                        {
                            DockContent DockForm = (DockContent)Plu.GetPluginWindow();
                            DockForm.Owner = this;
                            DockForm.Show(this.MainDockPanel,DockState.Float);
                        }
                    }
                    ToolStripMenuItem ViewMenu = new ToolStripMenuItem();
                    ViewMenu.Text = Plu.GetPluginWindow().Text;
                    ViewMenu.Tag = Plu.GetPluginWindow();
                    ViewMenu.Click += ViewMenu_Click;
                    ViewToolMenu.DropDownItems.Add(ViewMenu);
                }
                Plu.SetMenu(this.UIMainMenuStrip);
            }
        }

        void ViewMenu_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem Item = (ToolStripMenuItem)sender;
            if(Item.Tag!=null)
            {
                if(Item.Tag.GetType().BaseType==typeof(DockContent))
                {
                    DockContent PluDockForm = (DockContent)Item.Tag;
                    PluDockForm.Show(this.MainDockPanel);
                }
                else if(Item.Tag.GetType().BaseType==typeof(Form))
                {
                    Form PluForm = (Form)Item.Tag;
                    PluForm.Show(this);
                }
            }
        }

        private delegate void cm_aopdel(ClientManagerOperateEventArgs e);
        void ClientManager_AfterOperateClient(ClientManagerOperateEventArgs e)
        {
            if (Program.ClientManager.InvokeRequired)
            {
                cm_aopdel del = new cm_aopdel(ClientManager_AfterOperateClient);
                Program.ClientManager.BeginInvoke(del, e);
            }
            else
            {
                if (e.OperateType == ClientManagerOperateType.Add)
                {
                    ScreenViewerMini mini = new ScreenViewerMini(e.OperateClient);
                    mini.BorderStyle = BorderStyle.FixedSingle;
                    Program.ClientManager.flowLayoutPanel1.Controls.Add(mini);
                    Program.ClientList.AddClient(e.OperateClient);
                }
            }
        }

        private void tbtnSetting_Click(object sender, EventArgs e)
        {
            Program.SettingWnd.ShowDialog();
        }

        private void 服务端信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.ServerStats.Show(this.MainDockPanel);
        }

        private void tooliset1_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.SetSendImgRate(1000, ClientManager.GetAllClient(ClientState.Connected));
            ServerUIRateSetting.BitmapRefreshRate = 1000;
        }

        private void tooliset2_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.SetSendImgRate(2000, ClientManager.GetAllClient(ClientState.Connected));
            ServerUIRateSetting.BitmapRefreshRate = 2000;
        }

        private void tooliset5_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.SetSendImgRate(5000, ClientManager.GetAllClient(ClientState.Connected));
            ServerUIRateSetting.BitmapRefreshRate = 5000;
        }

        private void toolisetok_Click(object sender, EventArgs e)
        {
            int Rate = int.Parse(tooltsett.Text);
            ClientCommandCenter.SetSendImgRate(Rate, ClientManager.GetAllClient(ClientState.Connected));
            ServerUIRateSetting.BitmapRefreshRate = Rate;
        }

        private void tooltsett_Click(object sender, EventArgs e)
        {
            int o;
            if (!int.TryParse(tooltsett.Text, out o))
            {
                tooltsett.Text = ServerUIRateSetting.BitmapRefreshRate.ToString();
            }
        }

        private void btnStartWatch_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.StartSendBmp(ClientManager.GetAllClient(ClientState.Connected));
        }

        private void btnPauseWatch_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.PauseSendBmp(ClientManager.GetAllClient(ClientState.Connected));
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.RefreshImage(ClientManager.GetAllClient(ClientState.Connected));
        }

        private void toolset1616_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = (ToolStripDropDownItem)sender;
            ClientCommandCenter.SetImgSize(
                ToolClass.SplitSizeString(item.Text),
                ClientManager.GetAllClient(ClientState.Connected));
        }

        private void toolsetbmpsizeok_Click(object sender, EventArgs e)
        {
            ClientCommandCenter.SetImgSize(
                ToolClass.SplitSizeString(toolsetsizecus.Text),
                ClientManager.GetAllClient(ClientState.Connected));
        }

        private void 客户端管理ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.ClientManager.Show(this.MainDockPanel);
        }

        private void jpegToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripDropDownItem item = (ToolStripDropDownItem)sender;
            ClientCommandCenter.SetImgFormat(item.Text, ClientManager.GetAllClient(ClientState.Connected));
        }

        private void toolSign_Click(object sender, EventArgs e)
        {
            Program.SignWnd.ShowDialog();
        }

        private void toolSendMessage_Click(object sender, EventArgs e)
        {
            Program.SendMessageWnd.ReSetList();
            Program.SendMessageWnd.ShowDialog();
        }
        private void PingTimer_Tick(object sender, EventArgs e)
        {
            ClientCommandCenter.Ping(ClientManager.GetAllClient(ClientState.Connected));
        }

        private void toolSendFile_Click(object sender, EventArgs e)
        {
            Program.SendFileWnd.ShowDialog();
        }

        private void toolsettime_Click(object sender, EventArgs e)
        {
            this.tooltsett.Text = ServerUIRateSetting.BitmapRefreshRate.ToString();
        }

        private void MainWnd_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(ServerMain.GetState()!=ServerState.Created)
                MainDockPanel.SaveAsXml(Application.StartupPath + "//Layout.config");
        }

        private void 客户端列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.ClientList.Show(this.MainDockPanel);
        }

        private void 对象属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.ProperWnd.Show(this.MainDockPanel);
        }

        private void 输出窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.OutputWnd.Show(this.MainDockPanel);
        }

        private void 侦测客户端连接ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConnectCommand.ListenForClientConnect();
            //ServerObjects.UdpCommandCenter.SendCommand(CommandType.ServerStarted, new IPEndPoint(IPAddress.Broadcast, ServerGlobalSettingIpPort.ClientUdpListenPort));
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Program.AboutWnd.ShowDialog();
        }

    }
}
